# 装饰器
import time


def timeslong(func):
    def wrapper():
        start = time.perf_counter()
        print("开始倒计时")
        func()
        end = time.perf_counter()
        print(f"Function took {end - start} seconds")
    return wrapper

@timeslong
def add():
    y = 0
    for i in range(10):
        y = y + i
        print(y)
    return y


import re


# 定义装饰器
def register_decorator(func):
    def wrapper(*args, **kwargs):
        # 在调用原函数之前进行校验
        username = kwargs.get('username')
        password = kwargs.get('password')

        # 用户名校验：假设用户名必须是非空，并且只能包含字母、数字和下划线
        if not username or not re.match(r'^\w+$', username):
            return "无效的用户名"

        # 密码校验：假设密码必须是非空，并且至少包含6个字符
        if not password or len(password) < 6:
            return "密码长度不能少于6个字符"

        # 如果校验通过，调用原始函数
        return func(*args, **kwargs)

    return wrapper



# 使用装饰器
@register_decorator
def register_user(username, password):
    print(f"注册用户：用户名={username}, 密码已隐藏")


# # 测试装饰器
# print(register_user(username="user123", password="mypassword"))  # 应该成功注册
# print(register_user(username="user", password="pass"))  # 密码太短
# print(register_user(username="user@", password="mypassword123"))  # 用户名无效


def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Something before the function is called.")
        result = func(*args, **kwargs)
        print("Something after the function is called.")
        return result
    return wrapper


@my_decorator
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("Kimi")